'use strict';
const db = uniCloud.database()
exports.main = async (event, context) => {
	//event为客户端上传的参数
	const {
		userId,
		avatarImg
	} = event;

	const user = await db.collection('user').doc(userId).get();
	const id = user.data[0].id
	const oldUrl = user.data[0].avatar;
	//尝试删除云存储内之前的图片信息
	try {
		uniCloud.deleteFile({
			fileList: [oldUrl]
		})
	} catch (e) {
		console.log(e)
	}
	//修改用户头像
	await db.collection('user').doc(userId).update({
		avatar: avatarImg
	})
	//修改文章作者头像
	await db.collection('article').where({
		'author.id': id
	}).update({
		'author.avatar': avatarImg
	})

	//返回数据给客户端
	return {
		code: 0,
		data: {
			msg: "头像更换成功"
		}
	}
};
